import React, { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { Card, CardContent, Typography, Button, Box, Divider, Paper, Chip } from '@mui/material';
import { MessageCircle, Clock, Calendar, Heart, Zap, AlertTriangle, CheckCircle, ChevronLeft } from 'lucide-react';
import { PieChart, Pie, Cell, ResponsiveContainer, BarChart, Bar, XAxis, YAxis, Tooltip, Legend } from 'recharts';
import { supabase } from '@/lib/supabase/client';
import { useToast } from '@/components/ui/use-toast';
import { motion } from 'framer-motion';
import Link from 'next/link';

// Define types based on Supabase schema
interface Session {
  id: string;
  user_id: string;
  session_type: 'emotion_regulation' | 'crisis_support' | 'goal_setting' | 'problem_solving' | 'exploration';
  started_at: string;
  ended_at: string | null;
  duration_seconds: number | null;
  primary_emotion: string | null;
  emotion_intensity: number | null;
  risk_level: 'low' | 'medium' | 'high' | 'critical';
  workflow_used: 'emotion_regulation' | 'crisis_support' | 'goal_setting' | 'problem_solving' | 'exploration' | null;
  user_satisfaction: number | null;
  therapeutic_progress: number | null;
  follow_up_needed: boolean;
  follow_up_scheduled_for: string | null;
  session_summary: string | null;
  therapist_notes: string | null;
  created_at: string;
}

interface Message {
  id: string;
  session_id: string;
  message_type: 'user' | 'agent' | 'system';
  content: string;
  agent_type: 'therapist' | 'coach' | 'mentor' | 'peer' | null;
  workflow_mode: 'emotion_regulation' | 'crisis_support' | 'goal_setting' | 'problem_solving' | 'exploration' | null;
  response_time_ms: number | null;
  emotion_analysis: any | null;
  crisis_assessment: any | null;
  therapeutic_interventions: any | null;
  timestamp: string;
  encrypted_content: string | null;
  retention_expires_at: string | null;
}

// Mock data for demonstration
const mockSession: Session = {
  id: '1',
  user_id: 'user_123',
  session_type: 'emotion_regulation',
  started_at: '2023-11-15T09:30:00Z',
  ended_at: '2023-11-15T10:15:00Z',
  duration_seconds: 2700,
  primary_emotion: 'anxiety',
  emotion_intensity: 75,
  risk_level: 'medium',
  workflow_used: 'emotion_regulation',
  user_satisfaction: 85,
  therapeutic_progress: 60,
  follow_up_needed: true,
  follow_up_scheduled_for: '2023-11-22T09:30:00Z',
  session_summary: 'This session focused on anxiety management techniques. The user reported feeling overwhelmed with work-related stress. We practiced deep breathing exercises and discussed time management strategies.',
  therapist_notes: 'User showed good engagement during the session. Recommended continuing with daily breathing exercises and keeping a stress journal. Scheduled follow-up to check progress.',
  created_at: '2023-11-15T09:30:00Z'
};

const mockMessages: Message[] = [
  {
    id: 'msg_1',
    session_id: '1',
    message_type: 'user',
    content: 'I\'ve been feeling really anxious lately, especially about work deadlines.',
    agent_type: null,
    workflow_mode: 'emotion_regulation',
    response_time_ms: null,
    emotion_analysis: { anxiety: 85, stress: 70, sadness: 20 },
    crisis_assessment: { risk_level: 'medium' },
    therapeutic_interventions: null,
    timestamp: '2023-11-15T09:30:15Z',
    encrypted_content: null,
    retention_expires_at: null
  },
  {
    id: 'msg_2',
    session_id: '1',
    message_type: 'agent',
    content: 'I\'m sorry to hear you\'re feeling anxious. Let\'s take a moment to focus on your breathing. Can you try taking a slow, deep breath in for 4 seconds, hold for 2, and then exhale for 6 seconds?',
    agent_type: 'therapist',
    workflow_mode: 'emotion_regulation',
    response_time_ms: 1200,
    emotion_analysis: null,
    crisis_assessment: null,
    therapeutic_interventions: { type: 'breathing_exercise', details: '4-2-6 breathing technique' },
    timestamp: '2023-11-15T09:31:05Z',
    encrypted_content: null,
    retention_expires_at: null
  },
  {
    id: 'msg_3',
    session_id: '1',
    message_type: 'user',
    content: 'I tried that breathing exercise. It helped a little bit, but I still feel worried about my deadlines.',
    agent_type: null,
    workflow_mode: 'emotion_regulation',
    response_time_ms: null,
    emotion_analysis: { anxiety: 70, stress: 65, calm: 30 },
    crisis_assessment: { risk_level: 'medium' },
    therapeutic_interventions: null,
    timestamp: '2023-11-15T09:33:20Z',
    encrypted_content: null,
    retention_expires_at: null
  },
  {
    id: 'msg_4',
    session_id: '1',
    message_type: 'agent',
    content: 'It\'s normal to still feel worried after one exercise. Let\'s talk about your deadlines. Can you break them down into smaller, more manageable tasks? Sometimes seeing them written out can make them feel less overwhelming.',
    agent_type: 'therapist',
    workflow_mode: 'emotion_regulation',
    response_time_ms: 1500,
    emotion_analysis: null,
    crisis_assessment: null,
    therapeutic_interventions: { type: 'cognitive_restructuring', details: 'Breaking down tasks' },
    timestamp: '2023-11-15T09:34:45Z',
    encrypted_content: null,
    retention_expires_at: null
  }
];

// Emotion data for chart
const emotionData = [
  { name: 'Anxiety', value: 75 },
  { name: 'Stress', value: 65 },
  { name: 'Calm', value: 25 },
  { name: 'Sadness', value: 20 },
  { name: 'Happiness', value: 10 }
];

// Progress data for chart
const progressData = [
  { name: 'Session 1', progress: 40 },
  { name: 'Session 2', progress: 50 },
  { name: 'Session 3', progress: 60 },
  { name: 'Session 4', progress: 60 },
];

// Colors
const COLORS = ['#FF8042', '#FFBB28', '#00C49F', '#8884d8', '#0088FE'];

export default function SessionDetail() {
  const params = useParams();
  const router = useRouter();
  const toast = useToast();
  const [session, setSession] = useState<Session | null>(null);
  const [messages, setMessages] = useState<Message[]>([]);
  const [loading, setLoading] = useState(true);
  const [showSummary, setShowSummary] = useState(true);
  const [showMessages, setShowMessages] = useState(false);
  const [showAnalysis, setShowAnalysis] = useState(false);

  const sessionId = params.id as string;

  useEffect(() => {
    // Fetch session details and messages from Supabase
    const fetchSessionDetails = async () => {
      try {
        setLoading(true);
        // In a real implementation, you would fetch from Supabase
        // const { data: sessionData, error: sessionError } = await supabase
        //   .from('therapy_sessions')
        //   .select('*')
        //   .eq('id', sessionId)
        //   .single();

        // const { data: messagesData, error: messagesError } = await supabase
        //   .from('conversation_messages')
        //   .select('*')
        //   .eq('session_id', sessionId)
        //   .order('timestamp', { ascending: true });

        // For now, use mock data if sessionId matches mock session
        setTimeout(() => {
          if (sessionId === mockSession.id) {
            setSession(mockSession);
            setMessages(mockMessages);
          } else {
            // Simulate session not found
            toast({ status: 'error', title: 'Session not found', description: 'The requested session could not be located.' });
            router.back();
          }
          setLoading(false);
        }, 800);
      } catch (error) {
        console.error('Error fetching session details:', error);
        toast({ status: 'error', title: 'Failed to load session', description: 'Please try again later.' });
        setLoading(false);
      }
    };

    fetchSessionDetails();
  }, [sessionId, router, toast]);

  // Calculate duration
  const getDurationString = () => {
    if (!session || !session.duration_seconds) return 'N/A';
    const minutes = Math.floor(session.duration_seconds / 60);
    const seconds = session.duration_seconds % 60;
    return `${minutes}m ${seconds}s`;
  };

  // Format date
  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen bg-gray-50">
        <motion.div
          initial={{ opacity: 0, scale: 0.8 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ duration: 0.5 }}
          className="flex flex-col items-center"
        >
          <div className="w-16 h-16 border-4 border-blue-500 border-t-transparent rounded-full animate-spin"></div>
          <Typography variant="h6" className="mt-4 text-blue-600">Loading session details...</Typography>
        </motion.div>
      </div>
    );
  }

  if (!session) {
    return null; // Shouldn't happen due to error handling
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white shadow-md">
        <div className="container mx-auto px-4 py-4 flex items-center justify-between">
          <div className="flex items-center space-x-2">
            <Button variant="text" color="inherit" onClick={() => router.back()} className="p-1">
              <ChevronLeft size={20} />
            </Button>
            <Typography variant="h5" className="font-bold text-blue-600">Session Details</Typography>
          </div>
          <Link href="/chat">
            <Button variant="contained" color="primary">
              Start New Session
            </Button>
          </Link>
        </div>
      </header>

      <main className="container mx-auto px-4 py-8">
        {/* Session Info Card */}
        <Card className="shadow-md mb-8 hover:shadow-lg transition-shadow duration-300">
          <CardContent>
            <div className="flex flex-col md:flex-row md:items-center md:justify-between mb-4">
              <div>
                <Typography variant="h5" className="font-bold text-gray-800 mb-1">
                  {session.session_type.charAt(0).toUpperCase() + session.session_type.slice(1)} Session
                </Typography>
                <div className="flex items-center text-gray-500 text-sm space-x-4">
                  <div className="flex items-center">
                    <Calendar size={16} className="mr-1" />
                    <span>{formatDate(session.started_at)}</span>
                  </div>
                  <div className="flex items-center">
                    <Clock size={16} className="mr-1" />
                    <span>{getDurationString()}</span>
                  </div>
                </div>
              </div>
              <Chip
                label={session.risk_level.charAt(0).toUpperCase() + session.risk_level.slice(1)}
                color={session.risk_level === 'high' || session.risk_level === 'critical' ? 'error' : session.risk_level === 'medium' ? 'warning' : 'success'}
                variant="outlined"
                className="mt-2 md:mt-0"
              />
            </div>

            <Divider className="my-4" />

            {/* Session Tabs */}
            <div className="flex border-b mb-6 overflow-x-auto scrollbar-hide">
              <Button
                variant={showSummary ? "contained" : "outlined"}
                color="primary"
                onClick={() => {
                  setShowSummary(true);
                  setShowMessages(false);
                  setShowAnalysis(false);
                }}
                className="flex-shrink-0"
              >
                Summary
              </Button>
              <Button
                variant={showMessages ? "contained" : "outlined"}
                color="primary"
                onClick={() => {
                  setShowSummary(false);
                  setShowMessages(true);
                  setShowAnalysis(false);
                }}
                className="flex-shrink-0 ml-2"
              >
                Conversation
              </Button>
              <Button
                variant={showAnalysis ? "contained" : "outlined"}
                color="primary"
                onClick={() => {
                  setShowSummary(false);
                  setShowMessages(false);
                  setShowAnalysis(true);
                }}
                className="flex-shrink-0 ml-2"
              >
                Analysis
              </Button>
            </div>

            {/* Summary Tab */}
            {showSummary && (
              <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                transition={{ duration: 0.3 }}
              >
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <Typography variant="subtitle1" className="font-bold text-gray-700 mb-2">Session Summary</Typography>
                    <Paper elevation={0} className="p-4 bg-blue-50 rounded-lg mb-4">
                      <Typography variant="body1" className="text-gray-800">
                        {session.session_summary || 'No summary available for this session.'}
                      </Typography>
                    </Paper>

                    <Typography variant="subtitle1" className="font-bold text-gray-700 mb-2 mt-6">Therapist Notes</Typography>
                    <Paper elevation={0} className="p-4 bg-green-50 rounded-lg">
                      <Typography variant="body1" className="text-gray-800">
                        {session.therapist_notes || 'No therapist notes available.'}
                      </Typography>
                    </Paper>
                  </div>

                  <div>
                    <Typography variant="subtitle1" className="font-bold text-gray-700 mb-2">Session Metrics</Typography>
                    <div className="space-y-4">
                      <div>
                        <div className="flex justify-between mb-1">
                          <Typography variant="body2" className="text-gray-600">Therapeutic Progress</Typography>
                          <Typography variant="body2" className="font-bold text-gray-800">{session.therapeutic_progress}%</Typography>
                        </div>
                        <div className="w-full bg-gray-200 rounded-full h-2.5">
                          <div className="bg-blue-600 h-2.5 rounded-full" style={{ width: `${session.therapeutic_progress}%` }}></div>
                        </div>
                      </div>

                      <div>
                        <div className="flex justify-between mb-1">
                          <Typography variant="body2" className="text-gray-600">User Satisfaction</Typography>
                          <Typography variant="body2" className="font-bold text-gray-800">{session.user_satisfaction}%</Typography>
                        </div>
                        <div className="w-full bg-gray-200 rounded-full h-2.5">
                          <div className="bg-green-600 h-2.5 rounded-full" style={{ width: `${session.user_satisfaction}%` }}></div>
                        </div>
                      </div>

                      <div>
                        <div className="flex justify-between mb-1">
                          <Typography variant="body2" className="text-gray-600">Primary Emotion</Typography>
                          <Typography variant="body2" className="font-bold text-gray-800">
                            {session.primary_emotion} ({session.emotion_intensity}%)
                          </Typography>
                        </div>
                        <div className="w-full bg-gray-200 rounded-full h-2.5">
                          <div className="bg-yellow-600 h-2.5 rounded-full" style={{ width: `${session.emotion_intensity}%` }}></div>
                        </div>
                      </div>
                    </div>

                    {session.follow_up_needed && (
                      <Paper elevation={1} className="p-4 mt-6 bg-amber-50 rounded-lg border-l-4 border-amber-500">
                        <div className="flex items-start">
                          <AlertTriangle size={20} className="text-amber-500 mr-2 mt-0.5 flex-shrink-0" />
                          <div>
                            <Typography variant="subtitle1" className="font-bold text-gray-800">Follow-up Needed</Typography>
                            <Typography variant="body2" className="text-gray-700">
                              Scheduled for: {formatDate(session.follow_up_scheduled_for!)}
                            </Typography>
                            <Button
                              variant="outlined"
                              color="warning"
                              size="small"
                              className="mt-2"
                            >
                              Reschedule
                            </Button>
                          </div>
                        </div>
                      </Paper>
                    )}
                  </div>
                </div>
              </motion.div>
            )}

            {/* Messages Tab */}
            {showMessages && (
              <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                transition={{ duration: 0.3 }}
                className="max-h-[600px] overflow-y-auto pr-2"
              >
                <div className="space-y-4">
                  {messages.map((message) => (
                    <div key={message.id} className={`flex ${message.message_type === 'user' ? 'justify-end' : 'justify-start'}`}>
                      <div className={`max-w-[80%] p-3 rounded-lg ${message.message_type === 'user' ? 'bg-blue-100 text-right' : 'bg-white text-left shadow-sm'}`}>
                        <Typography variant="body1" className="text-gray-800">
                          {message.content}
                        </Typography>
                        <Typography variant="caption" className="text-gray-500 block mt-1">
                          {new Date(message.timestamp).toLocaleTimeString()}
                        </Typography>
                        {message.therapeutic_interventions && (
                          <Chip
                            label={`Intervention: ${message.therapeutic_interventions.type}`}
                            size="small"
                            color="primary"
                            variant="outlined"
                            className="mt-2"
                          />
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              </motion.div>
            )}

            {/* Analysis Tab */}
            {showAnalysis && (
              <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                transition={{ duration: 0.3 }}
              >
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <Typography variant="subtitle1" className="font-bold text-gray-700 mb-3">Emotion Analysis</Typography>
                    <div className="h-64 bg-white p-4 rounded-lg shadow-sm">
                      <ResponsiveContainer width="100%" height="100%">
                        <PieChart>
                          <Pie
                            data={emotionData}
                            cx="50%"
                            cy="50%"
                            labelLine={false}
                            outerRadius={80}
                            fill="#8884d8"
                            dataKey="value"
                            label={({ name, percent }) => `${name}: ${(percent ? percent * 100 : 0).toFixed(0)}%`}
                          >
                            {emotionData.map((entry, index) => (
                              <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                            ))}
                          </Pie>
                          <Tooltip />
                        </PieChart>
                      </ResponsiveContainer>
                    </div>
                  </div>

                  <div>
                    <Typography variant="subtitle1" className="font-bold text-gray-700 mb-3">Therapeutic Progress</Typography>
                    <div className="h-64 bg-white p-4 rounded-lg shadow-sm">
                      <ResponsiveContainer width="100%" height="100%">
                        <BarChart
                          data={progressData}
                          margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
                        >
                          <XAxis dataKey="name" />
                          <YAxis />
                          <Tooltip />
                          <Bar dataKey="progress" name="Progress %" fill="#0088FE" />
                        </BarChart>
                      </ResponsiveContainer>
                    </div>
                  </div>
                </div>

                <div className="mt-6">
                  <Typography variant="subtitle1" className="font-bold text-gray-700 mb-3">Key Insights</Typography>
                  <Paper elevation={0} className="p-4 bg-purple-50 rounded-lg">
                    <Typography variant="body2" className="text-gray-800 mb-3">
                      <strong>Emotion Patterns:</strong> The primary emotion detected was anxiety at 75% intensity. This is consistent with the user's report of work-related stress.
                    </Typography>
                    <Typography variant="body2" className="text-gray-800 mb-3">
                      <strong>Therapeutic Effectiveness:</strong> Breathing exercises showed a 15% reduction in anxiety levels during the session.
                    </Typography>
                    <Typography variant="body2" className="text-gray-800">
                      <strong>Recommendations:</strong> Continue with daily breathing exercises and implement time management strategies discussed. Monitor stress levels and schedule follow-up session as recommended.
                    </Typography>
                  </Paper>
                </div>
              </motion.div>
            )}
          </CardContent>
        </Card>

        {/* Action Cards */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-8">
          <Link href="/mood">
            <Card className="shadow-md hover:shadow-lg transition-shadow duration-300 hover:scale-105 cursor-pointer">
              <CardContent className="flex flex-col items-center text-center p-6">
                <Heart className="h-8 w-8 text-red-500 mb-3" />
                <Typography variant="h6" className="font-bold text-gray-800 mb-1">Track Your Mood</Typography>
                <Typography variant="body2" className="text-gray-600">Log your feelings after this session</Typography>
              </CardContent>
            </Card>
          </Link>

          <Link href="/goals">
            <Card className="shadow-md hover:shadow-lg transition-shadow duration-300 hover:scale-105 cursor-pointer">
              <CardContent className="flex flex-col items-center text-center p-6">
                <CheckCircle className="h-8 w-8 text-green-500 mb-3" />
                <Typography variant="h6" className="font-bold text-gray-800 mb-1">Review Goals</Typography>
                <Typography variant="body2" className="text-gray-600">Update your therapeutic objectives</Typography>
              </CardContent>
            </Card>
          </Link>

          <Link href="/exercises">
            <Card className="shadow-md hover:shadow-lg transition-shadow duration-300 hover:scale-105 cursor-pointer">
              <CardContent className="flex flex-col items-center text-center p-6">
                <Zap className="h-8 w-8 text-yellow-500 mb-3" />
                <Typography variant="h6" className="font-bold text-gray-800 mb-1">Quick Exercises</Typography>
                <Typography variant="body2" className="text-gray-600">Try recommended coping strategies</Typography>
              </CardContent>
            </Card>
          </Link>
        </div>
      </main>
    </div>
  );
}